package com.sky.utils;

import java.security.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@Data
@Slf4j
@ConfigurationProperties(prefix = "keygen")
public class KeyGenerationUtil {

    // 配置文件中的私钥和公钥保存路径
    private String privateKeyPath;
    private String publicKeyPath;

    // 生成 RSA 密钥对并保存到文件
    public void generateAndSaveKeyPair() throws NoSuchAlgorithmException, IOException {
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 密钥长度为 2048 位
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 获取公钥和私钥
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        // 保存私钥到文件
        try (FileOutputStream privateKeyOut = new FileOutputStream(privateKeyPath)) {
            privateKeyOut.write(privateKey.getEncoded());
        }

        // 保存公钥到文件
        try (FileOutputStream publicKeyOut = new FileOutputStream(publicKeyPath)) {
            publicKeyOut.write(publicKey.getEncoded());
        }

        log.info("生成 RSA 密钥对并将其保存到文件");
    }

    // 从文件加载私钥
    public PrivateKey loadPrivateKey() throws Exception {
        byte[] privateKeyBytes = Files.readAllBytes(Paths.get(privateKeyPath));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(privateKeyBytes));
    }

    // 从文件加载公钥
    public PublicKey loadPublicKey() throws Exception {
        byte[] publicKeyBytes = Files.readAllBytes(Paths.get(publicKeyPath));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(new java.security.spec.X509EncodedKeySpec(publicKeyBytes));
    }

}
